from datetime import datetime
import json
from app.models.db_setup import db


class CartShare(db.Model):
    """购物车分享记录模型"""

    __tablename__ = "CartShare"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    share_code = db.Column(db.String(50), unique=True, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey("User.id"), nullable=False)
    cart_item_ids = db.Column(db.Text, nullable=False)  # 存储为JSON字符串
    created_at = db.Column(db.DateTime, default=datetime.now)
    expires_at = db.Column(db.DateTime)
    is_active = db.Column(db.Boolean, default=True)

    # 关联关系
    user = db.relationship("User", backref=db.backref("shared_carts", lazy=True))

    def __init__(self, share_code, user_id, cart_item_ids, expires_at=None):
        self.share_code = share_code
        self.user_id = user_id
        self.cart_item_ids = json.dumps(cart_item_ids)  # 将列表转换为JSON字符串
        self.expires_at = expires_at
        self.is_active = True

    def get_cart_item_ids(self):
        """获取购物车项目ID列表"""
        return json.loads(self.cart_item_ids)

    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "shareCode": self.share_code,
            "userId": self.user_id,
            "cartItemIds": self.get_cart_item_ids(),
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "expiresAt": self.expires_at.isoformat() if self.expires_at else None,
            "isActive": self.is_active,
        }
